<?php
namespace app\admin\model;
use think\facade\Session;
use think\Model;

class Base extends Model
{
    /**
     * 后台左侧菜单权限,仅展示到二级
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getMenus()
    {
        $authRule = AuthRule::where('status', 1)
            ->order('sort asc')
            ->select()
            ->toArray();
        $menus = array();
        foreach ($authRule as $key => $val) {
            $authRule[$key]['href'] = url($val['name']);
            //先把顶级菜单放到menus里
            if ($val['pid'] == 0) {
                if (Session::get('admin.id') != 1) {
                    if (in_array($val['id'], Session::get('admin.rules', []))) {
                        $menus[] = $val;
                    }
                } else {
                    $menus[] = $val;
                }
            }
        }
        foreach ($menus as $k => $v) {
            $menus[$k]['children'] = [];
            foreach ($authRule as $kk => $vv) {
                if ($v['id'] == $vv['pid']) {
                    if (Session::get('admin.id') != 1) {
                        if (in_array($vv['id'], Session::get('admin.rules'))) {
                            $menus[$k]['children'][] = $vv;
                        }
                    } else {
                        $menus[$k]['children'][] = $vv;
                    }
                }
            }
        }
        return $menus;
    }
    /**
     * 返回layui的table所需要的格式
     * @author sin
     * @param $post
     * @return mixed
     */
    public function tableData($post)
    {
        if(isset($post['limit'])){
            $limit = $post['limit'];
        }else{
            $limit = config('paginate.list_rows');
        }
        $tableWhere = $this->tableWhere($post);
        $list = $this
            ->where($tableWhere['where'])
            ->order('id asc')
            ->paginate($limit);
        $total=$list->total();
        $re['code'] = 0;
        $re['msg'] = '';
        $re['count'] = $total;
        $re['data'] = $list->getCollection();
        return $re;
    }
    /**
     * 根据输入的查询条件，返回所需要的where
     * @author sin
     * @param $post
     * @return mixed
     */
    protected function tableWhere($post)
    {
        $where = [];
        if(isset($post['title']) && $post['title'] != ""){
            $where[] = ['title', 'like', '%'.$post['title'].'%'];
        }
        $result['where'] = $where;
        $result['field'] = "*";
        $result['order'] = [];
        return $result;
    }
}